package com.zenjava.jfx.performance.animate1;

import javafx.animation.Animation;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Animate1App extends Application {

    public static void main(String[] args) throws Exception {
        launch(args);
    }

    public void start(Stage stage) throws Exception {

        final StackPane rootPane = new StackPane();

        Canvas background = new Canvas(800, 600);
        GraphicsContext g = background.getGraphicsContext2D();
        g.setFill(Color.YELLOW);
        g.fillRect(0, 0, 800, 600);
        rootPane.getChildren().add(background);

        Rectangle box1 = new Rectangle(40, 40);
        box1.setFill(Color.RED);
        createTranslation(box1, 5, -500, -500, 500, 500).play();
        rootPane.getChildren().add(box1);

        Rectangle box2 = new Rectangle(40, 40);
        box2.setFill(Color.BLUE);
        createTranslation(box2, 3, 500, -500, -500, 500).play();
        rootPane.getChildren().add(box2);

        Rectangle box3 = new Rectangle(40, 40);
        box3.setFill(Color.GREEN);
        createTranslation(box3, 3, -500, 0, 500, 0).play();
        rootPane.getChildren().add(box3);

        Scene scene = new Scene(rootPane, 1200, 800);
        stage.setScene(scene);
        stage.show();
    }

    protected TranslateTransition createTranslation(Node node, int seconds, int fromX, int fromY, int toX, int toY) {
        TranslateTransition transition = new TranslateTransition(Duration.seconds(seconds), node);
        transition.setCycleCount(Animation.INDEFINITE);
        transition.setAutoReverse(true);
        transition.setFromX(fromX);
        transition.setFromY(fromY);
        transition.setToX(toX);
        transition.setToY(toY);
        return transition;
    }
}
